<template>
  <div class="song-audio">
    <audio id="player" :src="url" controls="controls" preload="true" @canplay="startPlay" @ended="ended">

    </audio>
  </div>
</template>

<script>
import {mapGetters} from "vuex"
export default {
  name: "SongAudio",
  data() {
    return {


    }
  },
  computed:{
    ...mapGetters([
      'id',
      'url',
      'isPlay'
    ])
  },
  created() {

  },
  watch:{
    // 监听当前音乐状态，是暂停还是播放
    isPlay:function(){
      this.togglePlay()
    }
  },
  methods: {
    // 获取链接后准备播放
    startPlay(){
      let player=document.querySelector('#player')
      // 开始播放
      player.play()
    },
    // 播放完成后触发
    ended(){
      this.isPlay=false
    },
    // 暂停开始播放
    togglePlay(){
      let player=document.querySelector('#player')
      if(this.isPlay){
        player.play()
      }else {
        player.pause()
      }
    }
  }
}
</script>

<style scoped>
.song-audio{
  display: none;
}
</style>
